#!/bin/bash

echo "﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎﹍﹎"
echo "安装东方通WebServer..."
set -eo pipefail

# 当前位置是 "项目文件夹/web-server"
ori_path=$(pwd)
project_path=$(cd `dirname $0`; pwd)
echo $project_path
cd $project_path

# 返回上一级 项目文件夹
cd ../


jar_name=$(ls -1 -F -r ./target/*.jar | head -1)

echo "当前文件夹: $(pwd) ,jar_name: ${jar_name}"

if [ "$jar_name" == "" ]; then
    echo "找不到Jar包！退出"
    cd $ori_path
    echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊"
    exit
fi

echo "mv -n web-server/*-tongweb.sh  ./res-runtime/"
mv -n web-server/*-tongweb.sh  ./res-runtime/

function process(){
  target="$1"


  fc=$(ls $target/tomcat-embed-core-*.jar -l | grep "^-"| wc -l)
  if [ $fc -eq 0 ]; then
      echo "找不到 $target/tomcat-embed-core-* 包, $fc！退出"
      return
  fi

  rm -f $target/tomcat-embed-core-*
  rm -f $target/tomcat-embed-el-*

  mv -n web-server/tongweb-embed-*.jar web-server/tongweb-spring-boot-starter-2.x-*.jar $target

#  mv -n web-server/tongweb-jsp-*.jar  $target

  fc=$(ls $target/tomcat-embed-websocket-*.jar -l |grep "^-"| wc -l)
  if [ $fc -gt 0 ]; then
      rm -f $target/tomcat-embed-websocket-*.jar
    mv -n web-server/tongweb-spring-boot-websocket-2.x-*.jar  $target
  fi

  echo "完成Jar包替换， ls $target/tongweb*"
  ls $target/tongweb*
}

mkdir -p ./target/lib
fc=$(ls ./target/lib/tomcat-embed-* -l |grep "^-"| wc -l)
if [ $fc -gt 0 ]; then
  echo "处理 lib 文件夹"


  process ./target/lib

  cd $ori_path
  echo "完成东方通WebServer"
  echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊"
  exit 0
fi


echo "处理 $jar_name"
echo "unzip -q $jar_name -d jar-unzip"
unzip -q $jar_name -d jar-unzip
rm -f $jar_name

process jar-unzip/BOOT-INF/lib


cd jar-unzip


echo "jar cf0M  ../$jar_name *"
jar cf0M  ../$jar_name *

cd $ori_path
echo "完成东方通WebServer"
echo "﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊﹉﹊"